﻿<%@ WebHandler Language="C#" Class="RbApsPlanShipConfirmHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

public class RbApsPlanShipConfirmHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSDispatchIBusiness uMESDispatchbusiness = uMESBusinessFactory.instance.GetuLMSDispatchObject();
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    RbContainerBusiness rbBusiness = new RbContainerBusiness();
    string rbFactoryID = System.Configuration.ConfigurationManager.AppSettings["RBFactoryID"].ToString(); //热表ID
    string toAppID_RB = System.Configuration.ConfigurationManager.AppSettings["ToAppID_RB"].ToString(); //数据中心推送目的ID（热表）

    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "GetApsPlanShipOutDatas":
                    GetApsPlanShipOutDatas(context);
                    break;
                case "SaveRbApsPlanShipOut":
                    SaveRbApsPlanShipOut(context);
                    break;
                case "SaveRbApsPlanShipReceive":
                    SaveRbApsPlanShipReceive(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 获取转工转出的数据
    /// </summary>
    /// <param name="context"></param>
    public void GetApsPlanShipOutDatas(HttpContext context)
    {
        StringBuilder sql = new StringBuilder();
        sql.AppendLine(@"SELECT Distinct c.mfgordername,c.productdescription description,c.containerid,c.containername,c.workflowstepname,s.stepno || '-' || s.description stepname,ap.apsplandetailid,
                        ap.confirmdate,e.fullname confirmempname,ap.shipreceivedate,ee.fullname receiveempname,s.stepseq,wb.workflowname || ':' || w.workflowrevision workflowinfo,
                        ai.starttime,ai.endtime,ai.createdate,NVL(ap.shipstatus,0) shipstatus
                        FROM apsplandetail2 ap 
                        LEFT JOIN apsplaninfo ai ON ai.apsplaninfoid = ap.apsplaninfoid
                        LEFT JOIN workflow w ON w.workflowid = ai.workflowid
                        LEFT JOIN workflowbase wb ON wb.workflowbaseid = w.workflowbaseid
                        LEFT JOIN containercurrentinfo c ON c.containerid = ap.containerid
                        LEFT JOIN stepinfo s ON s.stepinfoid = ap.stepinfoid
                        LEFT JOIN employee e ON e.employeeid = ap.confirmempid
                        LEFT JOIN employee ee ON ee.employeeid = ap.shipreceiveempid
                        WHERE ap.isuse = 0 AND c.containerstatus = 1 AND c.isinstore = 0 ");
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        if (dic.ContainsKey("scanContainer") && !string.IsNullOrWhiteSpace(dic["scanContainer"].ToString()))
        {
            dic["scanContainer"] = commonBusiness.ContainerScan(dic["scanContainer"]);
            sql.AppendFormat(" AND c.containername = '{0}'", dic["scanContainer"]);
        }
        if (dic.ContainsKey("scanOrder") && !string.IsNullOrWhiteSpace(dic["scanOrder"].ToString()))
        {
            sql.AppendFormat(" AND c.mfgordername = '{0}'", dic["scanOrder"]);
        }
        if (dic.ContainsKey("productName") && !string.IsNullOrWhiteSpace(dic["productName"].ToString()))
        {
            sql.AppendFormat(" AND c.productname LIKE '%{0}%'", dic["productName"]);
        }
        if (dic.ContainsKey("containerName") && !string.IsNullOrWhiteSpace(dic["containerName"].ToString()))
        {
            sql.AppendFormat(" AND c.containername LIKE '%{0}%'", dic["containerName"]);
        }
        if (dic.ContainsKey("planStartDate") && !string.IsNullOrWhiteSpace(dic["planStartDate"]))
        {
            dic["planStartDate"] = dic["planStartDate"] + " 00:00:00";
            sql.AppendFormat(" AND ai.starttime >= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", dic["planStartDate"]);
        }
        if (dic.ContainsKey("planEndDate") && !string.IsNullOrWhiteSpace(dic["planEndDate"]))
        {
            dic["planEndDate"] = dic["planEndDate"] + " 23:59:59";
            sql.AppendFormat(" AND ai.starttime <= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", dic["planEndDate"]);
        }
        if (dic.ContainsKey("status") && !string.IsNullOrWhiteSpace(dic["status"]))
        {
            if (dic["status"] == "0")
            {
                sql.AppendLine(" AND s.shipcycle IS NOT NULL");//表示可以转出的数据
            }
            sql.AppendFormat(" AND NVL(ap.shipstatus,'0') = '{0}'", dic["status"]);
        }
        sql.AppendLine(" ORDER BY c.containerid,s.stepseq");
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(dic["pageIndex"]);
        pageDto.PageSize = int.Parse(dic["pageSize"]);
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存排产转工转出确认
    /// </summary>
    /// <param name="context"></param>
    public void SaveRbApsPlanShipOut(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtAps = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        string updateSql = "UPDATE apsplandetail2 ap SET ap.shipstatus = '1',ap.confirmdate = SYSDATE,ap.confirmempid = '{0}' WHERE ap.apsplandetailid = '{1}' AND NVL(ap.shipstatus,'0') = '0'";
        ArrayList sqlList = new ArrayList();
        foreach (DataRow item in dtAps.Rows)
        {
            sqlList.Add(string.Format(updateSql, m_UserInfo.EmployeeID, item["apsplandetailid"].ToString()));
        }
        DatabaseHelper.ExecuteSqlTran(sqlList);
        result.Message = "转出成功";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存排产转工接收
    /// </summary>
    /// <param name="context"></param>
    public void SaveRbApsPlanShipReceive(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtAps = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        string updateSql = "UPDATE apsplandetail2 ap SET ap.shipstatus = '2',ap.shipreceivedate = SYSDATE,ap.shipreceiveempid = '{0}' WHERE ap.apsplandetailid = '{1}' AND NVL(ap.shipstatus,'0') = '1'";
        ArrayList sqlList = new ArrayList();
        foreach (DataRow item in dtAps.Rows)
        {
            sqlList.Add(string.Format(updateSql, m_UserInfo.EmployeeID, item["apsplandetailid"].ToString()));
        }
        DatabaseHelper.ExecuteSqlTran(sqlList);
        result.Message = "接收成功";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}